//
//  ViewController.m
//  VideoVerbDemo
//
//  Created by hodor on 2019/8/15.
//  Copyright © 2019 王松锋. All rights reserved.
//

#import "ViewController.h"
// 判断iPhone X
#define HX_Is_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

//判断iPHoneXr
#define HX_Is_iPhoneXR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO)

//判断iPHoneXs
#define HX_Is_iPhoneXS ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

//判断iPhoneXs Max
#define HX_Is_iPhoneXS_MAX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO)

#define HX_IS_IPhoneX_All (HX_Is_iPhoneX || HX_Is_iPhoneXR || HX_Is_iPhoneXS || HX_Is_iPhoneXS_MAX)

// 导航栏 + 状态栏 的高度
#define hxNavigationBarHeight (HX_IS_IPhoneX_All ? 88 : 64)
#define hxTopMargin (HX_IS_IPhoneX_All ? 44 : 0)

#define hxBottomMargin (HX_IS_IPhoneX_All ? 34 : 0)

#define hxCollectionViewY 25

#define VideoY (HX_IS_IPhoneX_All ? 44 : 20)

#define hxValidRectX 30
#define hxImageWidth 8

@interface ViewController ()
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) UIView *videoView;
@property (strong, nonatomic) AVPlayer *player;
@property (nonatomic ,strong) AVPlayerItem *playerItem;
@property (strong, nonatomic) AVAsset *avAsset;

@property(nonatomic,assign)CGFloat itemWidth;
@property(nonatomic,assign)CGFloat itemHeight;

@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) NSTimer *indicatorLineTimer;

@property (strong, nonatomic) VideoEditBottomView *bottomView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
//    self.videoSize = CGSizeMake(920, 520);
    self.videoSize = CGSizeMake(720, 1280);
    self.itemHeight = 60;
    self.itemWidth = self.itemHeight / 16 * 9;
    
    [self endImageSize];
    
    [self Config];
    [self changeSubviewFrame];
    
    NSLog(@"朴实asdqafwasff");
    
    NSLog(@"asfafaffsafsdfsdzffszfsf");
    
}


-(void)Config{
    NSURL *videoUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"downloadVideo.MP4" ofType:nil]];
    self.avAsset = [AVAsset assetWithURL:videoUrl];
    self.playerItem = [AVPlayerItem playerItemWithAsset:self.avAsset];
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    [self.playerLayer setPlayer:self.player];
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    self.videoView.userInteractionEnabled=YES;
    [self.videoView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playPauseClick)]];
    
    [self.view addSubview:self.videoView];
    [self.view addSubview:self.bottomView];
    self.bottomView.itemHeight= self.itemHeight;
    self.bottomView.endImageSize = self.endImageSize;
    self.bottomView.itemWidth = self.itemWidth;
    self.bottomView.itemHeight = self.itemHeight;
}

- (void)changeSubviewFrame {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGFloat itemH = self.itemHeight;
    CGFloat bottomMargin = hxBottomMargin;
    CGFloat bottomX = 0;
    CGFloat bottomH = hxCollectionViewY + itemH + 5 + 50;
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        bottomX = hxBottomMargin;
        bottomMargin = 0;
    }
    //    self.bottomView.editView.validRect = CGRectZero;
    self.bottomView.frame = CGRectMake(bottomX, self.view.frame.size.height - bottomH - bottomMargin, self.view.frame.size.width - bottomX * 2, bottomH + bottomMargin);
    self.videoView.frame = [self getVideoRect];
    NSLog(@"%@",NSStringFromCGRect([self getVideoRect]));
    self.playerLayer.frame = self.videoView.bounds;
}

- (AVPlayerLayer *)playerLayer {
    if (!_playerLayer) {
        _playerLayer = [[AVPlayerLayer alloc] init];
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return _playerLayer;
}
- (UIView *)videoView {
    if (!_videoView) {
        _videoView = [[UIView alloc] init];
        [_videoView.layer addSublayer:self.playerLayer];
    }
    return _videoView;
}
- (CGSize)endImageSize
{
    if (_endImageSize.width == 0 || _endImageSize.height == 0) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = [UIScreen mainScreen].bounds.size.height;
        CGFloat imgWidth = self.videoSize.width;
        CGFloat imgHeight = self.videoSize.height;
        CGFloat w;
        CGFloat h;
        imgHeight = width / imgWidth * imgHeight;
        if (imgHeight > height) {
            w = height / self.videoSize.height * imgWidth;
            h = height;
        }else {
            w = width;
            h = imgHeight;
        }
        _endImageSize = CGSizeMake(w, h);
    }
    return _endImageSize;
}

//根据 视频自身的 宽高
- (CGRect)getVideoRect {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGFloat bottomMargin = hxBottomMargin;
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        bottomMargin = 0;
    }
    CGFloat bottomH = hxCollectionViewY + self.itemHeight + 5 + 50;
    CGFloat videoH = self.view.frame.size.height - bottomH - (VideoY) - bottomMargin;
    CGFloat videoW = self.view.frame.size.width - 30 * 2;
    CGFloat width = videoW;
    CGFloat height = videoH;
    CGFloat imgWidth = self.videoSize.width;
    CGFloat imgHeight = self.videoSize.height;
    CGFloat w;
    CGFloat h;
    imgHeight = width / imgWidth * imgHeight;
    if (imgHeight > height) {
        w = height / self.videoSize.height * imgWidth;
        h = height;
    }else {
        w = width;
        h = imgHeight;
    }
    
    return CGRectMake(30 + (videoW - w) / 2, VideoY + (videoH - h) / 2, w, h);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = _playerItem.status;
        if (status == AVPlayerItemStatusReadyToPlay) {
            [self SJVideoReadyToPlay];
            [self.playerItem removeObserver:self forKeyPath:@"status"];
        
        }else if (status == AVPlayerItemStatusFailed){
            NSLog(@"系统播放器无法播放视频=== %@",keyPath);
        }
    }
}

-(void)SJVideoReadyToPlay{
    self.playerStatus = PlayerStatusPlayingBeforeSeek;
    [self playVideo];
    self.bottomView.avAsset = self.avAsset;
}
- (void)playVideo {
    [self.player play];
    self.playerStatus = PlayerStatusPlaying;
}
#pragma mark  播放完成
- (void)moviePlayDidEnd:(NSNotification *)notification {
    [self.player pause];
    AVPlayerItem *p = [notification object];
//    [p seekToTime:CMTimeMake(self.mediaConfig.startTime * 1000, 1000) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    [self.player play];
}

-(void)playPauseClick{
    if (self.playerStatus==PlayerStatusPause) {
        self.playerStatus=PlayerStatusPlaying;
        [self.player play];
    }else{
        self.playerStatus=PlayerStatusPause;
        [self.player pause];
    }
}

- (void)startTimer {
    [self stopTimer];
    if (!self.avAsset || self.bottomView.interval == -1) {
        return;
    }
//    NSTimeInterval duration = [self getValidRectVideoTime];
    
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(playPartVideo:) userInfo:nil repeats:YES];
    [self.timer fire];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
//    [self.bottomView startLineAnimationWithDuration:duration];
}
- (void)stopTimer {
    
    [self.indicatorLineTimer invalidate];
    self.indicatorLineTimer = nil;
    
    [self.timer invalidate];
    self.timer = nil;
//    [self.bottomView removeLineView];
    [self.playerLayer.player pause];
}

//- (NSTimeInterval)getValidRectVideoTime {
//    CGFloat rectW = self.bottomView.editView.validRect.size.width;
//    CGFloat contentW = self.bottomView.contentWidth;
//    NSTimeInterval second = rectW / contentW * roundf([self getVideoTime]);
//    return roundf(second);
//}

#pragma mark - < 懒加载 >
- (VideoEditBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[VideoEditBottomView alloc] init];
        _bottomView.backgroundColor = [UIColor clearColor];
        
    }
    return _bottomView;
}



@end










@interface VideoEditBottomView()
<
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout
>

@property (strong, nonatomic) UIButton *cancelBtn;
@property (strong, nonatomic) UIButton *doneBtn;
@property (strong, nonatomic) AVAssetImageGenerator *generator;
@property (strong, nonatomic) NSOperationQueue *operationQueue;
@property (strong, nonatomic) NSMutableDictionary *operationDict;
@property (assign, nonatomic) NSInteger dataCount;
@property (assign, nonatomic) NSInteger videoSecond;

@property (assign, nonatomic) CGRect currentIndicatorLineFrame;
@property (nonatomic, strong) UIButton *progressView;

@property(strong,nonatomic) NSMutableArray * itemImageArray;
@end


@implementation VideoEditBottomView
- (void)dealloc {
    [self.operationQueue cancelAllOperations];
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self==[super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}
- (void)setup {
    self.itemImageArray = [NSMutableArray array];
    self.interval = -1;
    
    self.contentWidth = self.frame.size.width - hxValidRectX * 2 - hxImageWidth * 2;
    [self addSubview:self.collectionView];
    [self addSubview:self.cancelBtn];
    [self addSubview:self.doneBtn];
    [self addSubview:self.editView];

}


#pragma mark - < 懒加载 >
- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_cancelBtn addTarget:self action:@selector(didCancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}
- (UIButton *)doneBtn {
    if (!_doneBtn) {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_doneBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _doneBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _doneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_doneBtn addTarget:self action:@selector(didDoneBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _flowLayout.minimumInteritemSpacing = 0;
        _flowLayout.minimumLineSpacing = 0;
        _flowLayout.sectionInset = UIEdgeInsetsMake(0, hxValidRectX + hxImageWidth, 0, hxValidRectX + hxImageWidth);
    }
    return _flowLayout;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[HXVideoEditBottomViewCell class] forCellWithReuseIdentifier:@"CellId"];
#ifdef __IPHONE_11_0
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
#else
            if ((NO)) {
#endif
            }
        }
        return _collectionView;
}
    
- (EditFrameView *)editView {
    if (!_editView) {
        _editView = [[EditFrameView alloc] init];
//        _editView.delegate = self;
    }
    return _editView;
}
    
    
- (AVAssetImageGenerator *)generator {
    if (!_generator) {
        _generator = [[AVAssetImageGenerator alloc] initWithAsset:self.avAsset];
        if (self.endImageSize.width >= self.endImageSize.height / 9 * 15) {
            _generator.maximumSize = CGSizeMake(self.endImageSize.width, self.endImageSize.height);
        }else {
            _generator.maximumSize = CGSizeMake(self.endImageSize.width / 3, self.endImageSize.height / 3);
        }
        _generator.appliesPreferredTrackTransform = YES;
        _generator.requestedTimeToleranceBefore = kCMTimeZero;
        _generator.requestedTimeToleranceAfter = kCMTimeZero;
        _generator.apertureMode = AVAssetImageGeneratorApertureModeProductionAperture;
    }
    return _generator;
}
    
    
- (NSOperationQueue *)operationQueue {
    if (!_operationQueue) {
        _operationQueue = [[NSOperationQueue alloc] init];
        _operationQueue.maxConcurrentOperationCount = 5;
    }
    return _operationQueue;
}
    
- (NSMutableDictionary *)operationDict {
    if (!_operationDict) {
        _operationDict = [NSMutableDictionary dictionary];
    }
    return _operationDict;
}
    
#pragma mark - < UICollectionViewDataSource >
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemImageArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HXVideoEditBottomViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CellId" forIndexPath:indexPath];
    cell.imageView.image=_itemImageArray[indexPath.row];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item < self.dataCount - 1) {
        return CGSizeMake(self.itemWidth, self.itemHeight);
    }
    CGFloat itemW = self.contentWidth - indexPath.item * self.itemWidth;
    return CGSizeMake(itemW, self.itemHeight);
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//    [self getVideoFrameWithIndexPath:indexPath];
}
    
    
    
- (void)getVideoFrameWithIndexPath:(NSIndexPath *)indexPath {
    if (![self.operationDict objectForKey:@(indexPath.item).stringValue]) {
        NSBlockOperation *operation = [self getVideoFrameWithIndex:indexPath.item];
        [self.operationQueue addOperation:operation];
        [self.operationDict setObject:operation forKey:@(indexPath.item).stringValue];
    }
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
//    if (self.operationDict[@(indexPath.item).stringValue]) {
//        NSBlockOperation *operation = self.operationDict[@(indexPath.item).stringValue];
//        [operation cancel];
//        [self.operationDict removeObjectForKey:@(indexPath.item).stringValue];
//    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if (self.scrollViewDidScroll) {
//        self.scrollViewDidScroll();
//    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    if (!decelerate) {
//        if (self.startTimer) {
//            self.startTimer();
//        }
//    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    if (self.startTimer) {
//        self.startTimer();
//    }
}
    
- (void)layoutSubviews {
    CGFloat collectionViewW = self.frame.size.width;
    self.collectionView.frame = CGRectMake(0, hxCollectionViewY, collectionViewW, self.itemHeight);
    
    self.editView.frame = self.collectionView.frame;
    if (CGRectEqualToRect(self.editView.validRect, CGRectZero)) {
        self.editView.validRect = CGRectMake(hxValidRectX + hxImageWidth, 0, collectionViewW - hxValidRectX * 2 - hxImageWidth * 2, self.itemHeight);
    }
    
    self.cancelBtn.frame = CGRectMake(12, CGRectGetMaxY(self.collectionView.frame) + 15, 60, 40);
    
    self.doneBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-60-12, CGRectGetMaxY(self.collectionView.frame) + 15, 60, 40);
    
}
    
- (void)setValidRectX:(CGFloat)validRectX {
    _validRectX = validRectX;
    self.editView.itemWidth = self.itemWidth;
    self.editView.itemHeight = self.itemHeight;
    self.editView.validRectX = validRectX;
}
-(void)setAvAsset:(AVAsset *)avAsset{
    _avAsset = avAsset;
    self.interval = 1;
    CGFloat second = roundf(CMTimeGetSeconds(self.avAsset.duration));
    if (second <= 0) second = 1;
    self.editView.videoTime = second;
    self.videoSecond = second;
    CGFloat maxWidth = self.frame.size.width - hxValidRectX * 2 - hxImageWidth * 2;
    // 一个item代表多少秒
    CGFloat singleItemSecond;
    NSInteger maxVideoTime = 20;
    if (second <= maxVideoTime) {
        CGFloat itemCount = maxWidth / self.itemWidth;
        singleItemSecond = second / itemCount;
        self.contentWidth = maxWidth;
        self.dataCount = ceilf(itemCount);
        self.interval = singleItemSecond;
    }else if (second > maxVideoTime) {
        CGFloat singleSecondWidth = maxWidth / (CGFloat)maxVideoTime;
        NSLog(@"%f",singleSecondWidth);
        
        self.contentWidth = singleSecondWidth * second;
        NSLog(@"%f",self.contentWidth);
        self.dataCount = ceilf(self.contentWidth / self.itemWidth);
        
        singleItemSecond = self.itemWidth / singleSecondWidth;
        NSLog(@"%f",singleItemSecond);
        self.interval = singleItemSecond;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    CMTime startTime = kCMTimeZero;
    CMTime endTime = CMTimeMakeWithSeconds(second, 1000);
    int i = 0;
    while (CMTIME_COMPARE_INLINE(startTime, <=, endTime)) {
        [array addObject:[NSValue valueWithCMTime:startTime]];
        i++;
        startTime = CMTimeMakeWithSeconds(i * self.interval, 1000);
    }
    
    
    __weak __typeof(self) weakSelf = self;
    __block int index = 0;
    [self.generator generateCGImagesAsynchronouslyForTimes:array completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (result == AVAssetImageGeneratorSucceeded) {
            UIImage *img = [[UIImage alloc] initWithCGImage:image];
            dispatch_sync(dispatch_get_main_queue(), ^{
                [weakSelf.itemImageArray addObject:img];
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
                [weakSelf.collectionView insertItemsAtIndexPaths:@[indexPath]];
                index++;
            });
        }
    }];
    
    
    self.editView.contentWidth = self.contentWidth;
    
    [self.collectionView reloadData];
    [self layoutSubviews];
}
    
- (CMTime)getTimeWithIndex:(CGFloat)index {
    CGFloat second = index;
    CMTime time;
    time = CMTimeMakeWithSeconds(second * self.interval, self.avAsset.duration.timescale + 100);
    NSLog(@"%d",self.avAsset.duration.timescale + 100);
    return time;
}
- (NSBlockOperation *)getVideoFrameWithIndex:(NSInteger)index {
    __weak typeof(self) weakSelf = self;
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSInteger item = index;
        CMTime time = [weakSelf getTimeWithIndex:(CGFloat)index];
        NSError *error;
        CGImageRef cgImg = [weakSelf.generator copyCGImageAtTime:time actualTime:NULL error:&error];
        if (!error && cgImg) {
            UIImage *image = [UIImage imageWithCGImage:cgImg];
            CGImageRelease(cgImg);
            [weakSelf getVideoFrameWithImage:image item:item];
        }else {
            CMTime tempTime;
            if (item >= 0 && item < weakSelf.dataCount - 2) {
                tempTime = [weakSelf getTimeWithIndex:item + 1];
            }else {
                tempTime = [weakSelf getTimeWithIndex:item - 1];
            }
            error = nil;
            cgImg = [weakSelf.generator copyCGImageAtTime:tempTime actualTime:NULL error:&error];
            if (!error && cgImg) {
                UIImage *image = [UIImage imageWithCGImage:cgImg];
                CGImageRelease(cgImg);
                [weakSelf getVideoFrameWithImage:image item:item];
            }
        }
    }];
    return operation;
}
- (void)getVideoFrameWithImage:(UIImage *)image item:(NSInteger)item {
    dispatch_async(dispatch_get_main_queue(), ^{
        HXVideoEditBottomViewCell *tempCell = (HXVideoEditBottomViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
        if (tempCell) {
            CATransition *transition = [CATransition animation];
            transition.duration = 0.1f;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            transition.type = kCATransitionFade;
            tempCell.imageView.image = image;
            [tempCell.layer addAnimation:transition forKey:nil];
        }
    });
}
@end
    
    
    
    
    
    
@interface HXVideoEditBottomViewCell ()

@end

@implementation HXVideoEditBottomViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.imageView];
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
}
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
    }
    return _imageView;
}
@end
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
@interface EditFrameView ()
@property (strong, nonatomic) UIImageView *leftImageView;
@property (strong, nonatomic) UIImageView *rightImageView;
@property (assign, nonatomic) CGFloat minWidth;
@end
    
    

@implementation EditFrameView
    
-(instancetype)initWithFrame:(CGRect)frame{
    if (self==[super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}
  
- (void)setupUI {
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.5];
    [self addSubview:self.leftImageView];
    [self addSubview:self.rightImageView];
}
    
- (void)setContentWidth:(CGFloat)contentWidth {
    _contentWidth = contentWidth;
    if ((NSInteger)roundf(self.videoTime) <= 0) {
        self.minWidth = contentWidth;
        return;
    }
    CGFloat scale = (CGFloat)20 / self.videoTime;
    self.minWidth = contentWidth * scale;
    NSLog(@"%f===%f",contentWidth,self.minWidth);
}
    
    
-(void)panGestureAction:(UIPanGestureRecognizer*)ges{
    
}
    
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextClearRect(context, self.validRect);
    
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 4.0);
    
    CGPoint topPoints[2];
    topPoints[0] = CGPointMake(self.validRect.origin.x, 0);
    topPoints[1] = CGPointMake(self.validRect.size.width + self.validRect.origin.x, 0);
    
    CGPoint bottomPoints[2];
    bottomPoints[0] = CGPointMake(self.validRect.origin.x, self.itemHeight);
    bottomPoints[1] = CGPointMake(self.validRect.size.width + self.validRect.origin.x, self.itemHeight);
    
    CGContextAddLines(context, topPoints, 2);
    CGContextAddLines(context, bottomPoints, 2);
    
    CGContextDrawPath(context, kCGPathStroke);
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    CGRect left = self.leftImageView.frame;
    left.origin.x -= hxImageWidth * 2;
    left.size.width += hxImageWidth * 4;
    CGRect right = self.rightImageView.frame;
    right.origin.x -= hxImageWidth * 2;
    right.size.width = hxImageWidth * 4;
    
    if (CGRectContainsPoint(left, point)) {
        return self.leftImageView;
    }
    if (CGRectContainsPoint(right, point)) {
        return self.rightImageView;
    }
    return nil;
}
- (void)setValidRect:(CGRect)validRect {
    _validRect = validRect;
    self.leftImageView.frame = CGRectMake(validRect.origin.x - hxImageWidth, 0, hxImageWidth, self.itemHeight);
    self.rightImageView.frame = CGRectMake(validRect.origin.x + validRect.size.width, 0, hxImageWidth, self.itemHeight);
    
    [self setNeedsDisplay];
}

- (UIImageView *)leftImageView {
    if (!_leftImageView) {
        _leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hx_videoedit_left"]];
        _rightImageView.userInteractionEnabled = YES;
        _leftImageView.tag = 0;
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        [_leftImageView addGestureRecognizer:panGesture];
    }
    return _leftImageView;
}
- (UIImageView *)rightImageView {
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hx_videoedit_right"]];
        _rightImageView.userInteractionEnabled = YES;
        _rightImageView.tag = 1;
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        [_rightImageView addGestureRecognizer:panGesture];
    }
    return _rightImageView;
}
@end
    

